using System;
using System.Xml;

namespace AleaClasses
{
	/// <summary>
	/// TEdges defines one Edge in an Alea graph.
	/// </summary>
	public class TEdge: TTrackEdits
	{
		private TNode fFromNode = null;
		private TNode fToNode = null;
		private TLabel fLabel = null;

		private void Constructor(TNode aFromNode, TNode aToNode, TLabel aLabel)
		{
			fFromNode = aFromNode;
			fToNode = aToNode;
			fLabel = aLabel;
		}

		public TEdge(TNode aFromNode, TNode aToNode, TLabel aLabel, bool aNeedsSave)
		{
			Constructor(aFromNode, aToNode, aLabel);
			if (aNeedsSave)
				SetNeedsSave();
		}

		public TEdge(XmlElement aEdgeElem, TNodes aNodes, TLabels aLabels)
		{
			string lFromNodeCode;
			string lToNodeCode;
			string lLabelCode;

			TNode lFromNode = null;
			TNode lToNode = null;
			TLabel lLabel = null;

			XmlElement lValueElem = null;
			
			lValueElem = aEdgeElem.SelectSingleNode("FromNodeCode") as XmlElement;
			if (lValueElem != null)
			{
				lFromNodeCode = Convert.ToString(lValueElem.InnerText);
				lFromNode = aNodes.GetNodeByNodeCode(lFromNodeCode);
			}

			lValueElem = aEdgeElem.SelectSingleNode("ToNodeCode") as XmlElement;
			if (lValueElem != null)
			{
				lToNodeCode = Convert.ToString(lValueElem.InnerText);
				lToNode = aNodes.GetNodeByNodeCode(lToNodeCode);
			}

			lValueElem = aEdgeElem.SelectSingleNode("LabelCode") as XmlElement;
			if (lValueElem != null)
			{
				lLabelCode = Convert.ToString(lValueElem.InnerText);
				lLabel = aLabels.GetLabelByLabelCode(lLabelCode);
			}

			Constructor(lFromNode, lToNode, lLabel);
		}

		public XmlElement SaveToXml(XmlDocument aDoc)
		{
			XmlElement retval = null;
			XmlElement elem = null;

			retval = aDoc.CreateElement("Edge");

			if (FromNode != null)
			{
				elem = aDoc.CreateElement("FromNodeCode");
				elem.InnerText = FromNode.NodeCode;
				retval.AppendChild(elem);
			}

			if (ToNode != null)
			{
				elem = aDoc.CreateElement("ToNodeCode");
				elem.InnerText = ToNode.NodeCode;
				retval.AppendChild(elem);
			}

			if (Label != null)
			{
				elem = aDoc.CreateElement("LabelCode");
				elem.InnerText = Label.LabelCode;
				retval.AppendChild(elem);
			}

			return retval;
		}

		public TNode FromNode
		{
			get
			{
				return fFromNode;
			}
		}

		public TNode ToNode
		{
			get
			{
				return fToNode;
			}
			set
			{
				if (fToNode != value)
				{
					fToNode = value;
					SetNeedsSave();
				}
			}
		}

		public TLabel Label
		{
			get
			{
				return fLabel;
			}
			set
			{
				if (fLabel != value)
				{
					fLabel = value;
					SetNeedsSave();
				}
			}
		}
	}
}
